package com.noble.glamour.module.logic.socket.utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.noble.glamour.module.logic.socket.AutoConnectMgr;
import com.noble.glamour.module.logic.socket.TCPConstant;

/**
 * 心跳轮询
 */
public class HeartBeatUtil implements Handler.Callback {
    private volatile static HeartBeatUtil mInstance;

    private HeartBeatUtil() {
        initHandler();
    }

    public static HeartBeatUtil getInstance() {
        if (mInstance == null) {
            synchronized (HeartBeatUtil.class) {
                if (mInstance == null) {
                    mInstance = new HeartBeatUtil();
                }
            }
        }
        return mInstance;
    }

    private void initHandler() {
        Looper looper;
        if ((looper = Looper.myLooper()) != null) {
            poolHandler = new Handler(looper, this);
        } else if ((looper = Looper.getMainLooper()) != null) {
            poolHandler = new Handler(looper, this);
        } else {
            poolHandler = null;
        }
    }

    // ==========================================  心跳轮询  =====================================
    private static final int LOCATION_EVENT_START = 0x1;       // Handler msg
    private Handler poolHandler = null;
    private long reset_heartbeat = 0;    // 重置心跳间隔

    /**
     * 重置心跳间隔
     *
     * @param heartbeat 服务端分配心跳间隔：单位：s
     */
    public void resetHeartbeat(int heartbeat) {
        this.reset_heartbeat = heartbeat;
    }

    /**
     * 开启轮询
     */
    public void startHeartBeat() {
        stop();
        if (poolHandler == null) {
            initHandler();
        }
        if (reset_heartbeat <= 0) {
            reset_heartbeat = TCPConstant.Heartbeat_Time;
        }
        poolHandler.sendEmptyMessageDelayed(LOCATION_EVENT_START, reset_heartbeat);
    }

    /**
     * 关闭轮询
     */
    private void stop() {
        if (poolHandler != null) {
            poolHandler.removeMessages(LOCATION_EVENT_START);
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case LOCATION_EVENT_START:
                startHeartBeat();
                AutoConnectMgr.getInstance().heartbeat();
                break;
        }
        return false;
    }
}